package com.lanyou.cook.camel.util;

import java.net.URI;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.component.file.GenericFileEndpoint;
import org.apache.camel.component.file.remote.FtpComponent;
import org.apache.camel.component.file.remote.FtpConfiguration;
import org.apache.camel.component.file.remote.FtpUtils;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.commons.net.ftp.FTPFile;

/**
 * 继承FtpComponent，可按照需求改造
 * 
 * @author ly-lihailang
 *
 */
public class FtpComponentChild extends FtpComponent {
	public FtpComponentChild() {
		setEndpointClass(FtpEndpointChild.class);
	}

	public FtpComponentChild(CamelContext context) {
		super(context);
		setEndpointClass(FtpEndpointChild.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.camel.component.file.remote.FtpComponent#buildFileEndpoint
	 * (java.lang.String, java.lang.String, java.util.Map)
	 */
	protected GenericFileEndpoint<FTPFile> buildFileEndpoint(String uri,
			String remaining, Map<String, Object> parameters) throws Exception {
		String baseUri = getBaseUri(uri);
		FtpConfiguration config = new FtpConfiguration(new URI(baseUri));

		FtpUtils.ensureRelativeFtpDirectory(this, config);
		FtpEndpointChild<FTPFile> answer = new FtpEndpointChild<FTPFile>(uri,
				this, config);
		extractAndSetFtpClientConfigParameters(parameters, answer);
		extractAndSetFtpClientParameters(parameters, answer);
		extractAndSetFtpFileFilterParameters(parameters, answer);
		return answer;
	}
	
	/**
	 * 将uri中的ftpFileFilter参数存入FtpFileFilterParameters
	 * @param parameters uri传入的参数
	 * @param answer camel要创建的Endpoint
	 */
	protected void extractAndSetFtpFileFilterParameters(
			Map<String, Object> parameters, FtpEndpointChild<FTPFile> answer) {
		//判断uri中是否含有ftpFileFilter.，如果有则截取并保存到FtpFileFilterParameters
		if (IntrospectionSupport.hasProperties(parameters, "ftpFileFilter.")) {
			Map<String, Object> param = IntrospectionSupport.extractProperties(
					parameters, "ftpFileFilter.");
			answer.setFtpFileFilterParameters(param);
		}
	}
}
